﻿namespace ColumnOrderingSetup
{
    using System.Reflection;
    using System.Xml;

    using com.savealot.Extensions.AssemblyExtensions;
    using com.savealot.Extensions.SharePointExtensions;
    using com.savealot.SharePoint;

    using Microsoft.SharePoint;

    public class cobackgroundstatus_Definition : BaseDefinition
    {
        #region Fields

        const string LISTNAME = "cobackgroundstatus";
        const string SITECOLUMNS = "cobackgroundstatus.xml";

        #endregion Fields

        #region Constructors

        public cobackgroundstatus_Definition( SPFeatureReceiverProperties properties )
            : base(properties)
        {
        }

        ~cobackgroundstatus_Definition( )
        {
            Dispose( false );
        }

        #endregion Constructors

        #region Methods

        public override void Create( )
        {
            base.Create( );
            CreateSiteColumns( getFieldDefinitionsAsXml( SITECOLUMNS ) );
            createList( );
        }

        public override void Delete( )
        {
            base.Delete( );
            DeleteList( getListDefn( ), true );
            DeleteSiteColumns( getFieldDefinitionsAsXml( SITECOLUMNS ) );
        }

        void createList( )
        {
            CreateList( getListDefn( ) );
            using ( SPWeb spWeb = Properties.GetWeb( ) )
            {
                SPList spList = spWeb.Lists.GetListByRootFolder( LISTNAME );
                if ( spList != null )
                {
                    SPField spField = spWeb.Fields[ "Errors" ];
                    if ( spField != null && !spList.Fields.Contains( spField.Id ) )
                    {
                        spList.Fields.Add( spField );
                        spList.Update( );
                    }
                }
            }
        }

        XmlNodeList getFieldDefinitionsAsXml( string resource )
        {
            XmlNodeList fields = null;
            string s = Assembly.GetExecutingAssembly( ).GetFullyQualifiedManifestResourceName( resource );
            string xml = Assembly.GetExecutingAssembly( ).GetManifestResourceAsString( s );
            if ( !string.IsNullOrEmpty( xml ) )
            {
                XmlDocument d = new XmlDocument( );
                d.LoadXml( xml );
                XmlNode n = d.SelectSingleNode( "Fields" );
                fields = n.SelectNodes( "Field" );
            }
            return fields;
        }

        ListDefn getListDefn( )
        {
            return new ListDefn
            {
                RootFolderName = LISTNAME,
                Title = LISTNAME,
                Description = "Contains the status of background SPOT processes.",
                Hidden = true,
                HideExistingContentTypes = false
            };
        }

        #endregion Methods
    }
}